package com.weiyan.blog.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weiyan.blog.utils.EncryptUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author misterWei
 * @create 2020年01月21号:14点22分
 * @mailbox mynameisweiyan@gmail.com
 *
 * 对token 进行解析的过滤器链,加入security 中
 */
@Component
public class AuthFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        String token = httpServletRequest.getHeader("token");
        if (token != null) {
            String json = EncryptUtil.dncryptRAM(token);
            JSONObject jsonObject = JSON.parseObject(json);
            //获取用户身份信息
            String principal = jsonObject.getString("principal");
            //获取用户权限信息
            JSONArray authorities = jsonObject.getJSONArray("authorities");
            String[] authoritieArr = new String[authorities.size()];
            authorities.toArray(authoritieArr);

            //装载到安全容器中  1 用户信息 2凭证(可以为空) 3 权限
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(principal,null, AuthorityUtils.createAuthorityList(authoritieArr));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        }

        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
